package app.fugema.shop.main.login.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.view.View;

import com.base.common.model.http.err.ApiException;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.Base64Utils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.utils.span.SpanUtils;
import com.base.common.view.base.BaseActivity;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;

import androidx.annotation.NonNull;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.RegisterActivityBinding;
import app.fugema.shop.main.login.model.CheckImgResult;
import app.fugema.shop.main.login.model.RegisterResult;
import app.fugema.shop.main.login.vm.LoginVM;

public class RegisterActivity extends BaseActivity<RegisterActivityBinding, LoginVM>
{
    public static int REGISTER_REQ_CODE = 106;

    private CountDownTimer mCountDownTimer;
    //验证码
    private CheckImgResult imgCodeResult;

    public static void lunch(Activity context)
    {
        context.startActivityForResult(new Intent(context, RegisterActivity.class), REGISTER_REQ_CODE);
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_activity);
    }


    @Override
    protected void initView() {

        binding.ivBack.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                finish();
            }
        });

        //密码登录
        /*
        binding.btnGoLogin.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                LoginActivity.lunch(RegisterActivity.this);
                LiveEventBus.get(AppConstants.LOGIN_PASS, Integer.class).post(1);
                finish();
            }
        });
        */

        //重新获取验证码
        binding.ivVerCode.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view)
            {
                getVerfyCode();
            }
        });

        //注册
        binding.btnRegister.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                register();
            }
        });

        binding.etPhoneNO.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s)
            {
                if (s.toString().length() == 0)
                {
                    binding.btnRegister.setEnabled(false);
                    binding.btnRegister.setAlpha(0.6f);
                }
                else
                {
                    binding.btnRegister.setEnabled(true);
                    binding.btnRegister.setAlpha(1f);
                }
            }
        });
        // 手机号 分割
        //VerifyUtils.onTextChangedPhone(binding.etPhoneNO);

        String s = binding.etPhoneNO.getText().toString().trim();
        if (s.length() == 0)
        {
            binding.btnRegister.setEnabled(false);
            binding.btnRegister.setAlpha(0.6f);
        }

        binding.llCheckedText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                binding.ctvCheckedText.setChecked(!binding.ctvCheckedText.isChecked());
                if (binding.ctvCheckedText.isChecked())
                {
                    binding.ctvCheckedText.setBackgroundResource(R.mipmap.ic_radio_checked);

                    String s = binding.etPhoneNO.getText().toString().trim();
                    if (s.length() == 0)
                    {
                        binding.btnRegister.setEnabled(false);
                        binding.btnRegister.setAlpha(0.6f);
                    }
                    else
                    {
                        binding.btnRegister.setEnabled(true);
                        binding.btnRegister.setAlpha(1f);
                    }
                }
                else
                {
                    binding.ctvCheckedText.setBackgroundResource(R.mipmap.ic_radio_unchecked);
                    binding.btnRegister.setEnabled(false);
                    binding.btnRegister.setAlpha(0.6f);
                }

            }
        });

        SpanUtils.with(binding.tvContent)
                .append("同意" + UIUtils.getString(R.string.app_name))
                .append("《服务政策》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(0xff2892E4);
                        ds.setUnderlineText(false);
                    }

                    @Override
                    public void onClick(@NonNull View widget) {
                        UserAgreementActivity.lunch(getActivity(), true);
                    }
                })
                .append("和")
                .append("《隐私协议》")
                .setClickSpan(new ClickableSpan() {
                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(0xff2892E4);
                        ds.setUnderlineText(false);
                    }

                    @Override
                    public void onClick(@NonNull View widget) {
                        UserAgreementActivity.lunch(getActivity(), false);
                    }
                })
                .create();
    }


    @Override
    protected void initData()
    {
        //第一次 先获取 验证码
        getVerfyCode();
    }

    /**
     * 注册
     */
    private void register()
    {
        //String phoneNum = binding.etPhoneNO.getText().toString().replaceAll(" ", "");
        String uName = binding.etPhoneNO.getText().toString();
        String msgCode = binding.etMsgCode.getText().toString();
        String passWord = binding.etPassWord.getText().toString();
        String passWordRepeat = binding.etPassWordRepeat.getText().toString();

        if (uName.isEmpty())
        {
            UIUtils.showToastSafes("帐号不能为空");
            return;
        }

        if (msgCode.isEmpty())
        {
            UIUtils.showToastSafes("验证码不能为空");
            return;
        }

        if (passWord.isEmpty())
        {
            UIUtils.showToastSafes("密码不能为空");
            return;
        }

        if (passWord.length() < 6 || passWord.length() > 20)
        {
            UIUtils.showToastSafes("请设置6-20位新的登录密码");
            return;
        }


        if (!passWord.equals(passWordRepeat))
        {
            UIUtils.showToastSafes("两次密码不一样");
            return;
        }
        UserAgreementDialogFragment dialog = UserAgreementDialogFragment.newInstance(null, null);
        dialog.setListener(new UserAgreementDialogFragment.onUserAgreementItemClickListener() {
            @Override
            public void onSubmitClick()
            {

                viewModel.registerUser(uName, passWord, msgCode)
                        .observe(mContext, new BaseViewObserver<LiveDataWrapper<RegisterResult>>()
                        {
                            @Override
                            protected void onSuccess(LiveDataWrapper<RegisterResult> data)
                            {
                                if(data.data.isSuccess())
                                {
                                    UIUtils.showToastSafes("注册成功！");
                                    finish();
                                }
                                else
                                {
                                    //{"success":false,"msg":"用户名由4-20个中文英文数字字母下划线组成","code":104}
                                    UIUtils.showToastSafes(data.data.getMsg());
                                }
                            }

                            @Override
                            protected void onAppError(ApiException error)
                            {
                                super.onAppError(error);
                            }
                        });


                //检查 账户
                /*
                viewModel.isRegistered(phoneNum)
                        .observe(mContext, new BaseViewObserver<BaseDataWrapper<Boolean>>(mContext) {
                            @Override
                            protected void onSuccess(BaseDataWrapper<Boolean> data) {
                                if (data.getData()) {
                                    //已注册
                                    UIUtils.showToastSafes(data.getMsg());
                                } else {
                                    //未注册
                                }
                            }
                        });
                */

            }

            @Override
            public void onCancelClick() {
                removeFragment(dialog);
            }
        });
        addFragment(dialog);
    }

    /**
     * 获取验证码图片
     */
    private void getVerfyCode()
    {
        //获取 图片 验证码
        viewModel.getImgCheckCode()
                 .observe(this, new BaseViewObserver<LiveDataWrapper<CheckImgResult>>()
                 {
                        @Override
                        protected void onSuccess(LiveDataWrapper<CheckImgResult> data)
                        {
                            if( UIUtils.isNotEmpty( data.data.getFileContents() ) )
                            {
                                imgCodeResult = data.data;
                                //LogUtil.e( data.data.getFileContents() );
                                // 显示 图片验证码
                                binding.ivVerCode.setImageBitmap( Base64Utils.base64ToBitmap(data.data.getFileContents()) );
                            }
                        }

                        @Override
                        public boolean isEmptyData(LiveDataWrapper<CheckImgResult> data) {
                            return UIUtils.isEmpty( data.data );
                        }
                 });

        //UIUtils.showToastSafes(data.getMsg());
        //开始 倒计时
        //starTimeCountDown();
    }


    private final int mTotalCountDown = 60 * 1000;

    /**
     * 开始倒计时
     */
    private void starTimeCountDown()
    {
        //binding.btnSendCode.setEnabled(false);
        if (mCountDownTimer == null)
        {
            mCountDownTimer = new CountDownTimer(mTotalCountDown, 1000) {
                @Override
                public void onTick(long millisUntilFinished)
                {
                    LogUtil.e( (millisUntilFinished / 1000) + "s" );
                    //binding.btnSendCode.setText((millisUntilFinished / 1000) + "s");
                }

                @Override
                public void onFinish()
                {
                    //binding.btnSendCode.setEnabled(true);
                    //binding.btnSendCode.setText("获取验证码");
                }
            };
        }
        mCountDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }


}
